/*
 * @Description: 列表
 * @Author: Rfan
 * @Date: 2022-09-19 14:08:51
 * @LastEditTime: 2022-09-19 17:49:17
 */

import { useEffect, useMemo, useState } from 'react';
import { Button, Space, Table, Tag } from 'antd';
import classNames from 'classnames/bind';
import { cloneDeep } from 'lodash-es';
import { formatDate, isNullObj } from '@/utils';
import { useFormatMessage } from '@/utils/intlHelpers';
import { useLogContext } from '../contexts/LogContext';
import Detail from '@/view/logMgt/Log/components/dialogs/Detail';
import OperateList from '@/view/logMgt/Log/components/logList/OperateList';
import type { IPageQuery } from '@/interfaces/global';
import type { ColumnsType } from 'antd/es/table';
import styles from '../styles/pageList.module.scss';

const cx = classNames.bind(styles);

const PageList = (props: any) => {
  const { className } = props;
  const {
    logList,
    logType,
    selectLogNav,
    listCondition,
    selectItems,
    setSelectKey,
    initListCondition,
    setExportCols,
    getCovertLogListFunc,
    deleteLogFunc,
    stateFilter,
    stateColorFilter
  } = useLogContext();
  const formatMessage = useFormatMessage();
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [listQuery, setListQuery] = useState<IPageQuery>({
    pageNo: 1,
    pageSize: 10,
    param: {}
  });

  useEffect(() => {
    if (selectLogNav) {
      initListCondition({ logType: selectLogNav });

      setExportCols();
    }
  }, [selectLogNav]);

  useEffect(() => {
    if (listCondition.logType) {
      setListQuery((state) => ({
        ...state,
        param: {
          ...state.param,
          ...listCondition
        }
      }));
    }
  }, [listCondition]);

  useEffect(() => {
    if (listQuery && !isNullObj(listQuery.param)) {
      setLoading(true);
      getCovertLogListFunc(listQuery)
        .then((res: any) => {
          setTotal(res?.totalCount);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [listQuery]);

  /**
   * @description 切换页码触发
   * @param {number} page 页码
   * @param {number} pageSize 每页条目数
   */
  const pageChange = (page: number, pageSize: number) => {
    setListQuery((state) => ({
      ...state,
      pageNo: page,
      pageSize
    }));
  };

  /**
   * @description : 表格选项相关设置
   * @param {number} selectedRowKeys 选择的项目的KEY
   */
  const onSelectChange = (selectedRowKeys: number[]) => {
    setSelectKey(selectedRowKeys);
  };

  /**
   * @description:  表格多选配置
   */
  const rowSelection = {
    selectItems,
    onChange: onSelectChange
  };

  const [selectInfo, setSelectInfo] = useState(null);
  const [detailVisible, setDetailVisible] = useState(false);
  const showDetail = (info: any) => {
    setSelectInfo(info);
    setDetailVisible(true);
  };

  const columns: ColumnsType = [
    { title: '序号', dataIndex: 'id', key: 'id', align: 'center' },
    { title: '全宗', dataIndex: 'fondName', key: 'fondName', align: 'center' },
    {
      title: '档案类型',
      dataIndex: 'archiveTypeName',
      key: 'archiveTypeName',
      align: 'center'
    },
    {
      title: '文件标题',
      dataIndex: ['logContent', 'fileName'],
      key: 'fileName',
      align: 'center'
    },
    {
      title: '转换前格式',
      dataIndex: ['logContent', 'fmtSource'],
      key: 'fmtSource',
      align: 'center'
    },
    {
      title: '转换后格式',
      dataIndex: ['logContent', 'fmtTarget'],
      key: 'fmtTarget',
      align: 'center'
    },
    { title: '操作者', dataIndex: 'operatorName', key: 'operatorName', align: 'center' },
    {
      title: '操作时间',
      dataIndex: 'operatorTime',
      key: 'operatorTime',
      align: 'center',
      render: (text: any) => formatDate(text)
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      render: (text: any) => formatDate(text)
    },
    {
      title: '转换结果',
      dataIndex: ['logContent', 'status'],
      key: 'status',
      align: 'center',
      render: (text: any) => <Tag color={stateColorFilter(text)}>{stateFilter(text)}</Tag>
    },
    {
      title: formatMessage('tableAction'),
      key: 'action',
      className: cx('action-col'),
      align: 'center',
      render: (_text: any, record: any) => (
        <Space>
          <Button
            type="link"
            size="small"
            onClick={() => {
              showDetail(record);
            }}
          >
            详情
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => {
              deleteLogFunc(record.id);
            }}
          >
            删除
          </Button>
        </Space>
      )
    }
  ];

  useEffect(() => {
    if (selectLogNav) {
      const exportList = cloneDeep(columns);
      setExportCols(
        exportList.slice(0, -1).map((col: any) => {
          return {
            header: col.title,
            property:
              col.dataIndex instanceof Array
                ? col.dataIndex[col.dataIndex.length - 1]
                : col.dataIndex
          };
        })
      );
    }
  }, [selectLogNav]);

  return (
    <div className={className}>
      {logType === 'business' ? (
        <Table
          columns={columns}
          dataSource={logList}
          loading={loading}
          rowKey="id"
          scroll={{ x: 'max-content' }}
          rowSelection={rowSelection}
          bordered
          pagination={{
            current: listQuery.pageNo,
            pageSize: listQuery.pageSize,
            total,
            onChange: pageChange
          }}
        />
      ) : (
        <OperateList />
      )}

      {useMemo(() => {
        return (
          selectInfo && (
            <Detail
              data={selectInfo}
              visible={detailVisible}
              onClose={() => {
                setDetailVisible(false);
              }}
            />
          )
        );
      }, [detailVisible])}
    </div>
  );
};

export default PageList;
